<template>
  <div class="task-dialog">
    <el-dialog
      v-model="dialogVisible"
      @open="onOpen"
      @close="onClose"
      title="概览详情"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="default"
        label-width="0px"
        label-position="left"
      >
        <div class="task-form-title">任务名称</div>
        <el-form-item label="" prop="missionName">
          <!-- <el-input
            v-model="formData.missionName"
            placeholder="请输入任务名称"
            :maxlength="50"
            show-word-limit
            clearable
            disabled
          ></el-input> -->
          <span>{{ formData.missionName }}</span>
        </el-form-item>
        <div class="task-form-title">任务介绍</div>
        <el-form-item label="" prop="description">
          <!-- <editor v-model="formData.description" :min-height="192" /> -->
          <!-- <editor
            class="WangEditor"
            @select="getRichDescription"
            ref="childrenRef"
            :editValue="formData.description"
            v-if="dialogVisible"
          /> -->
          <!-- <editor v-model="formData.description" v-if="dialogVisible" /> -->
          <div v-html="formData.description"></div>
        </el-form-item>
        <div class="task-form-title">活动时间</div>
        <el-form-item label="" prop="taskTime">
          <!-- <el-date-picker
            type="datetimerange"
            v-model="formData.taskTime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :style="{ width: '100%' }"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="至"
            clearable
          ></el-date-picker> -->
          <span>{{ formData.taskTime[0] }}至{{ formData.taskTime[1] }}</span>
        </el-form-item>
        <div class="task-form-title">任务标签</div>
        <el-form-item label="" prop="labelList">
          <el-tag
            v-for="tag in formData.labelList"
            :key="tag"
            :disable-transitions="false"
          >
            {{ tag }}
          </el-tag>
          <!-- <el-input
            v-if="inputLabelVisible"
            ref="InputLabelRef"
            v-model="inputLabelValue"
            style="width: 150px"
            size="small"
            @keyup.enter="handleLabelInputConfirm"
            @blur="handleLabelInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showLabelInput"
          >
            + 新增标签
          </el-button> -->
        </el-form-item>
        <div class="task-form-title">
          <span> 任务清单</span>
          <!-- <el-button
            class="button-new-tag"
            size="small"
            @click="showcheckInput"
          >
            +
          </el-button> -->
        </div>

        <el-row
          v-for="(item, index) in formData.checkLists"
          :key="'check' + index"
          :gutter="30"
          class="check-list"
        >
          <el-col :span="11">{{ item.content }}</el-col>
          <el-col :span="11">{{ item.endTime }}</el-col>
          <el-col :span="2"
            ><el-button
              class="button-new-tag"
              @click="handleDelCheckList(index)"
              size="small"
            >
              -
            </el-button></el-col
          >
        </el-row>
        <el-row v-if="inputCheckVisible" :gutter="30">
          <el-col :span="11">
            <el-input
              v-model="inputCheckValue"
              placeholder="请输入检查项名称"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="11">
            <el-date-picker
              v-model="timeCheckValue"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择检查项截止时间"
              clearable
            ></el-date-picker>
          </el-col>
          <el-col :span="2">
            <el-button class="button-new-tag" @click="handleCheckConfirm">
              确定
            </el-button>
          </el-col>
        </el-row>
        <div class="task-form-title">成员</div>
        <el-form-item label="" prop="students">
          <div v-for="item in formData.userList" :key="item.id">
            {{ item.username }},
          </div>
          <!-- <el-button @click="addStudentShow">添加</el-button> -->
        </el-form-item>
         <div class="task-form-title">能力测量指标</div>
        <el-form-item label="" prop="target">
          <el-checkbox-group v-model="formData.target">
            <el-checkbox
              :label="item"
              :value="item"
              v-for="item in targetList"
              :key="item"
              disabled
            />
            />
          </el-checkbox-group>
        </el-form-item>
        <div class="task-form-title">学习资料</div>
        <el-form-item label="" prop="fileList">
          <!-- <el-upload
            ref="fileListUpload"
            v-model:file-list="fileList"
            :action="fileListAction"
            multiple
            :before-upload="fileListBeforeUpload"
            :headers="headers"
            :on-success="handleUploadSuccess"
          >
            <el-button size="small" type="primary">+点击上传</el-button>
          </el-upload> -->
          <el-row v-for="(item, index) in fileList" :key="'f' + index" style="width:100%">
            <el-col :span="16">{{ item.response.name }}</el-col>
            <el-col :span="8"
              ><el-button
                link
                type="primary"
                icon="Download"
                @click="download(item.response)"
                >下载</el-button
              ></el-col
            >
          </el-row>
        </el-form-item>
        <div class="task-form-title">软件工具</div>
        <el-form-item label="" prop="tools">
          <!-- <editor v-model="formData.tools" :min-height="192" /> -->
          <!-- <editor
            class="WangEditor"
            @select="getRichTools"
            ref="childrenRefTools"
            :editValue="formData.tools"
            v-if="dialogVisible"
          /> -->
          <!-- <editor
            v-model="formData.tools"
            v-if="dialogVisible"
            id="editorRef2"
          /> -->
          <div v-html="formData.tools"></div>
        </el-form-item>
        <div class="task-form-title">排序</div>
        <el-form-item label="" prop="sort">
          <!-- <el-input-number
            v-model="formData.sort"
            placeholder="请输入排序"
            clearable
          ></el-input-number> -->
          <span>{{formData.sort}}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
  <MemberList
    v-model="memberDialogVisible2"
    @confirm="addStudent"
    :checkedList="formData.userList"
    type="student"
    :projectId="props.projectId"
  ></MemberList>
</template>
<script setup>
import { getToken } from "@/utils/auth";
import { getTaskInfo } from "@/api/home/home";
import MemberList from "./memberList.vue";

const headers = ref({
  Authorization: "Bearer " + getToken(),
});
const fileListAction = ref(import.meta.env.VITE_APP_BASEURL + "/common/upload");
const { proxy } = getCurrentInstance();
const props = defineProps({
  currentTaskId: { type: String, default: "" },
  projectId: {
    type: String,
    default: "",
  },
});
const formRef = ref();
const memberDialogVisible2 = ref(false);
const targetList = ref(["A", "B", "C", "D", "E", "F", "G"]);
const data = reactive({
  formData: {
    missionName: "",
    informations: [],
    description: undefined,
    taskTime: [],
    labelList: [],
    sort: 0,
    checkLists: [],
    userList: [],
    tools: "",
  },
  rules: {
    missionName: [
      {
        required: true,
        message: "请输入任务名称",
        trigger: "blur",
      },
    ],
  },
});
const { formData, rules } = toRefs(data);
// 上传请求路径
// 上传文件列表
const fileList = ref([]);
/**
 * @name: 上传之前的文件判断
 * @description: 上传之前的文件判断，判断文件大小文件类型等
 * @param {*} file
 * @return {*}
 */
function fileListBeforeUpload(file) {
  let isRightSize = file.size / 1024 / 1024 < 2000;
  if (!isRightSize) {
    proxy.$modal.msgError("文件大小超过 2G");
  }
  return isRightSize;
}
// 弹窗设置
const dialogVisible = defineModel();
// 弹窗确认回调
const emit = defineEmits(["confirm"]);
/**
 * @name: 弹窗打开后执行
 * @description: 弹窗打开后执行方法
 * @return {*}
 */
function onOpen() {
  if (props.currentTaskId) {
    getList();
  }
}
//修改时初始化
function getList() {
  getTaskInfo({ id: props.currentTaskId }).then((response) => {
    formData.value.checkLists = response.data.checkLists;
    formData.value.missionName = response.data.missionName;
    formData.value.description = response.data.description;
    formData.value.tools = response.data.tools;
    formData.value.target = response.data.target?response.data.target.split(','):[];
    formData.value.taskTime = [
      response.data.startTime + " 00:00:00",
      response.data.endTime + " 00:00:00",
    ];
    formData.value.sort = response.data.sort;
    formData.value.labelList = response.data.labelList.map((item) => {
      return item.dictValue;
    });
    formData.value.userList = JSON.parse(
      JSON.stringify(response.data.userList)
    );
    fileList.value = response.data.informations.map((item) => {
      let i = {
        name: item.name,
        response: {
          url: item.url,
          fullurl: item.fullurl,
          name: item.name,
        },
      };
      return i;
    });
  });
}
/**
 * @name: 弹窗关闭时执行
 * @description: 弹窗关闭方法，重置表单
 * @return {*}
 */
function onClose() {
  formRef.value.resetFields();
  formData.value = {
    missionName: "",
    informations: [],
    description: "",
    taskTime: [],
    labelList: [],
    sort: 0,
    checkLists: [],
    userList: [],
    tools: "",
    target:[]
  };
  fileList.value = [];
  inputCheckValue.value = "";
  timeCheckValue.value = "";
  inputCheckVisible.value = false;
}
/**
 * @name: 弹窗取消
 * @description: 弹窗取消方法
 * @return {*}
 */
function close() {
  dialogVisible.value = false;
}
/**
 * @name: 弹窗表单提交
 * @description: 弹窗表单提交方法
 * @return {*}
 */
function handelConfirm() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    // TODO 提交表单

    // 回调父级组件
    let params = {
      checkLists: JSON.parse(JSON.stringify(formData.value.checkLists)),
      missionName: formData.value.missionName,
      description: formData.value.description,
      startTime: formData.value.taskTime[0],
      endTime: formData.value.taskTime[1],
      tools: formData.value.tools,
      sort: formData.value.sort,
      labelList: [],
      informations: [],
      id: props.currentTaskId ? props.currentTaskId : "",
      userList: JSON.parse(JSON.stringify(formData.value.userList)),
    };
    params.labelList = formData.value.labelList.map((item) => {
      let i = {
        dictValue: item,
        dictCode: "",
      };
      return i;
    });
    params.informations = fileList.value.map((item) => {
      let i = {
        url: item.response.url,
        fullurl: item.response.fullurl,
        name: item.response.name,
      };
      return i;
    });
    console.log("params");
    emit("confirm", params);
    close();
  });
}
function handleUploadSuccess(res) {}
//标签处理
const inputLabelValue = ref("");
const inputLabelVisible = ref(false);
const InputLabelRef = ref(null);
function handleLabelClose(tag) {
  formData.value.labelList.splice(formData.value.labelList.indexOf(tag), 1);
}

function showLabelInput() {
  inputLabelVisible.value = true;
  nextTick(() => {
    InputLabelRef.value.focus();
  });
}

function handleLabelInputConfirm() {
  if (inputLabelValue.value) {
    formData.value.labelList.push(inputLabelValue.value);
  }
  inputLabelVisible.value = false;
  inputLabelValue.value = "";
}

//任务清单处理
const inputCheckVisible = ref(false);
const inputCheckValue = ref("");
const timeCheckValue = ref("");
function showcheckInput() {
  inputCheckVisible.value = true;
}
function handleCheckConfirm() {
  if (inputCheckValue.value == "" || timeCheckValue.value == "") {
    proxy.$modal.msgError("不可填入空值");
    return;
  }
  formData.value.checkLists.push({
    content: inputCheckValue.value,
    endTime: timeCheckValue.value,
  });
  inputCheckVisible.value = false;
  inputCheckValue.value = "";
  timeCheckValue.value = "";
}
function handleDelCheckList(i) {
  let no = -1;
  formData.value.checkLists.find((item, index) => {
    if (index == i) {
      no = index;
    }
  });
  formData.value.checkLists.splice(no, 1);
}
// 添加学生弹窗打开
function addStudentShow() {
  memberDialogVisible2.value = true;
}
// 添加学生
function addStudent(params) {
  formData.value.userList = params.map((item) => {
    let i = {
      id: item.id,
      username: item.username,
    };
    return i;
  });
}
//当编辑器的内容更新时，获取该值
const getRichDescription = function (value) {
  formData.value.description = value;
};
//当编辑器的内容更新时，获取该值
const getRichTools = function (value) {
  formData.value.tools = value;
};

/** 下载文件 */
function download(item) {
  proxy.download(
    "/common/download",
    {
      fileName: item.url.replace("/profile/upload", ""),
      delete: false,
    },
    item.name
  );
}
</script>
<style lang="scss">
.el-upload__tip {
  line-height: 1.2;
}
.task-dialog {
  .el-dialog {
    .el-dialog__body {
      height: 500px;
      overflow-y: auto;
      .task-form-title {
        margin: 20px 0;
        border-left: 3px solid rgb(64, 158, 255);
        padding: 0 10px;
        font-weight: bold;
      }
      .el-form {
        width: 90%;
        .el-tag {
          margin-right: 10px;
        }
        .check-list {
          padding: 10px;
          &:nth-child(even) {
            background: rgba(64, 158, 255, 0.2);
          }
        }
      }
    }
  }
}
</style>
